package com.example.rabbit.controller;

import com.example.rabbit.config.PriorityConfig;
import com.example.rabbit.config.SeniorConfirmConfig;
import com.rabbitmq.client.AMQP;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 生产者
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/9 17:41
 * @Version 1.0.0
 * @Description
 **/
@Slf4j
@Api("HelloController")
@RestController
@RequestMapping("/sendMessage")
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/senior")
    public void sendMessage() {
        //消息唯一性
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());

        String message = "hello rabbitMQ";
        rabbitTemplate.convertAndSend(SeniorConfirmConfig.CONFIRM_EXCHANGE, SeniorConfirmConfig.CONFIRM_ROUTING_KEY, message, correlationData);

        CorrelationData correlationData2 = new CorrelationData();
        correlationData2.setId("2");
        rabbitTemplate.convertAndSend(SeniorConfirmConfig.CONFIRM_EXCHANGE, SeniorConfirmConfig.CONFIRM_ROUTING_KEY + "xxx", message, correlationData2);
        log.info("消息发送完成");

    }

    /**
     * 发送优先级消息
     * 测试时，第一次运行先将  优先级消息 消费者关闭(@Component注解)。运行后，在控制台可以看到由10条消息
     * 第二次运行时，将 优先级消息 消费者开发(@Component注解),打印日志可以看出来优先消费
     */
    @GetMapping("/p")
    public void sendPriorityMessage() {
        String message = "priority rabbitMQ message";

        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder().priority(10).build();

        for (int i = 0; i < 10; i++) {
            //消息唯一性
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(UUID.randomUUID().toString());
            if (i == 5) {
                rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, i + message, (Message messageProcessor) -> {
                    MessageProperties messageProperties = messageProcessor.getMessageProperties();
                    messageProperties.setPriority(10);
                    return messageProcessor;
                });
            } else {
                rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, i + message, correlationData);
            }
        }


        log.info("消息发送完成");
    }
}
